package com.flightgame.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class FlightDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	@Transactional
	public void addFlight(Flight flight){
		try{
			sessionFactory.getCurrentSession().persist(flight);
			}
		catch(Exception sq){
			sq.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public List<Flight> getFlights(){
		return sessionFactory.getCurrentSession().createQuery("from Flight").list();
	}
	
	public Flight getUserFlight(int ownershipId){
		return (Flight) sessionFactory.getCurrentSession().createQuery("from Flight where ownershipid=:ownershipid").setParameter("ownershipid",ownershipId).uniqueResult();
	}
	
	@SuppressWarnings("unchecked")
	public List<Flight> getFlightsOnBoundedCoordinates(double lat1,double lat2,double lon1,double lon2){
		return sessionFactory.getCurrentSession().createQuery("from Flight where  lat > :lat1 AND lat < :lat2 AND lon > :lon1 AND lon < :lon2").setDouble("lat1",lat1).setDouble("lat2",lat2).setDouble("lon1",lon1).setDouble("lon2",lon2).list();
	} 
	
	@Transactional
	public void updateFlight(int ownershipId,double newLat,double newLon,double newAlt,String latLonHistory){
		Flight flight = getUserFlight(ownershipId);
		
		flight.setLat(newLat);
		flight.setLon(newLon);
		flight.setAltitude(newAlt);
		flight.setLatlonHistory(latLonHistory);
		
		sessionFactory.getCurrentSession().update(flight);
	}
	
	@Transactional
	public void deleteFlight(int ownershipId){
		Flight flight = getUserFlight(ownershipId);
		sessionFactory.getCurrentSession().delete(flight);
	}
}
